<?php

namespace App\Http\Controllers;

use App\Services\SubService;
use App\Subsidy;
use App\UsersOrders;
use DB;
use Illuminate\Http\Request;

class UserOrderController extends BaseController
{
    /**
     * 用户下单
     * @param Request $request
     */
    public function createOrder(Request $request){
        $this->uid = \session('uid');
        $subId = $request->subId;
        $SubService = new SubService();
        $orderId = 0;
        $res = $SubService->createOrder($this->uid, $subId, $orderId);
        if( $res ){
            return returnJson(0, '', ['orderId'=>$orderId]);
        }

        return returnJson(1, $SubService->msg);
    }

    /**
     * 检查当前任务最新订单状态
     * @param Request $request
     */
    public function checkSubOrder(Request $request){
        $this->uid = \session('uid');
        $subId = $request->subId;
        $SubService = new SubService();
        $orderId = 0;
        $res = $SubService->checkSubOrder($this->uid, $subId, $orderId);
        if( $res ){
            //有订单，并在待提交初审状态
            return returnJson(0, '', ['orderId'=>$orderId]);
        }

        return returnJson(1, $SubService->msg);
    }

    /**
     * 取消下单
     * @param Request $request
     */
    public function cancelOrder(Request $request){
        $this->uid = \session('uid');
        $orderId = $request->orderId;
        $SubService = new SubService();
        $res = $SubService->cancelOrder($this->uid, $orderId);
        if( $res ){
            return returnJson();
        }

        return returnJson(1, $SubService->msg);
    }

    /**
     * 订单列表(普通用户)
     */
    public function orderList(){
        $this->uid = \session('uid');
        $page = request()->input('page', 1);
        $list = UsersOrders::join("stores_info","stores_info.id",'=','users_orders.store_info_id')
            ->where('users_orders.uid', $this->uid)
            ->select("users_orders.*","stores_info.type as plate")
            ->limit(10)->offset(($page-1)*10)->orderBy('status', 'asc')->orderBy('id', 'desc')->get();
        foreach ($list as $key => &$value) {
            if( !$value->subsidy || $value->subsidy->status != 1 || $value->subsidy->is_deleted != 0 || $value->subsidy->is_frozen != 0 || !$value->storeInfo || !$value->store ){
                $value->sub_status = 0;
            }else{
                $value->sub_status = 1;
            }
        }
        return returnJson(0, '', ['list'=>$list]);
    }

    /**
     * 订单详情
     */
    public function orderDetail(){
        $id = request()->input('id', 1);
        $data = UsersOrders::find($id);
        $data->store = $data->store;
        $data->subsidy = $data->subsidy;
        return returnJson(0, '', $data);
    }

    /**
     * 初审提交审核
     */
    public function auditFirst(){
        $this->uid = \session('uid');
        $id = \request()->input('id');
        $imgurl = \request()->input('imgurl');
        $amount = \request()->input('amount');
        $orderNo = \request()->input('orderNo');
        $orderNo = str_replace(" ", "", $orderNo);
        $order = UsersOrders::where([
            ['id', $id],
            ['uid', $this->uid],
        ])->first();
        if( !$order ){
            return returnJson(1, '订单有误');
        }

        if( !in_array($order->status, [0, 10]) ){
            return returnJson(1, '订单状态无法上传');
        }

        if( DB::table('users_orders')->where('user_order_no', $orderNo)->whereIn('status', [10, 20,25,30,32,35,40,50])->where('id', '!=', $id)->count() ){
            return returnJson(1, '订单号重复，无法重复提交');
        }

        if( $amount < $order->max_money ){
            return returnJson(1, '订单金额未达到满减金额');
        }
        
        $order->imgs = $imgurl;
        $order->amount = $amount;
        $order->user_order_no = $orderNo;
        $order->is_need_ali_audit = 0;
        $order->is_first_remind = 0;
        $order->is_first_fail_remaid = 0;
        if( $order->status == 0 ){
            //第一次提交初审
            $order->sub_time1 = date('Y-m-d H:i:s', time()+ config("app.first_audit_time"));
        }else{
            //重新提交初审
            $order->sub_time1 = date('Y-m-d H:i:s', time()+ config("app.first_refuse_audit_time"));
        }
        $order->status = 20;
        
        if( $order->save() ){
            return returnJson();
        }
        return returnJson(1, '提交初审失败,请重新提交');
    }

    /**
     * 第一次复审提交审核
     */
    public function auditSecond(){
        $this->uid = \session('uid');
        $id = \request()->input('id');
        $imgurl = \request()->input('imgurl');
        $taste = \request()->input('taste')??2;
        $weight = \request()->input('weight')??2;
        $leak = \request()->input('leak')??2;
        $advise = \request()->input('advise')??"";
        $order = UsersOrders::where([
            ['id', $id],
            ['uid', $this->uid],
        ])->first();
        if( !$order ){
            return returnJson(1, '订单有误');
        }

        if( !in_array($order->status, [25,30]) ){
            return returnJson(1, '订单状态无法上传');
        }

        $order->status = 35;
        $order->img2 = $imgurl;
        $order->taste = $taste;
        $order->weight = $weight;
        $order->leak = $leak;
        $order->advise = $advise;
        $order->is_second_fail_remaid = 0;
        $order->is_complete_remind = 0;
        $order->sub_time2 = date('Y-m-d H:i:s');
        if( $order->save() ){
            return returnJson();
        }
        return returnJson(1, '提交复审失败,请重新提交');
    }

    /***********商户操作订单************/
    /**
     * 订单列表(商户)
     */
    public function merchantOrderList(){
        $this->uid = \session('uid');
        // $page = request()->input('page', 1);
        $type = request()->input('type', 1);//类型：1-待处理，2-驳回，3-已完成
        $date = request()->input('date');//日期
        $time = 0;
        //基础服务费
        $fee = \DB::table('config')->where('key', 'fee')->value('value');
        //当前折扣
        $nowFee = \DB::table('fee_activity')->where('start', '<', \getDt())->where('end', '>', \getDt())->orderBy('id', 'desc')->value('discount');
        $fee = $nowFee ? round($fee*$nowFee/10, 2) : $fee;

        //总计
        $allAmount = 0;
        //总服务费
        $allFee = 0;

        $notSettle = 0;
        $auditOkCount = 0;
        $auditFailCount = 0;

        
        if( $type <3 ){
            $subids = \DB::table('users_orders')->where('store_uid', $this->uid)->pluck('sub_id');
            if( !count($subids) ){
                return \returnJson(0, '', []);
            }
            $data = \DB::table('stores_info as si')->join('stores as s', 'si.store_id' , '=', 's.id')->join('subsidy as sub', 'si.id' , '=', 'sub.store_info_id')->whereIn('sub.id', $subids)->select(['s.*', 'sub.id as sid', 'si.title', 'si.type', 'sub.max_money', 'sub.return_money', 'sub.good_comment_type'])->get()->toArray();
            foreach ($data as $key => &$value) {
                switch ( $type ){
                    case 1://待处理
                        $notSettle = \DB::table('users_orders')->where('store_uid', $this->uid)->whereIn('status', [35,40])->count();
                        $auditOkCount = \DB::table('users_orders')->where('store_uid', $this->uid)->where('status', 40)->count();
                        $time = time();
                        $value->list = \DB::table('users_orders')->where('sub_id', $value->sid)->whereIn('status', [35,40])->orderBy('status', 'asc')->get()->toArray();
                        break;
                    case 2://驳回
                        $value->list = \DB::table('users_orders')->where('sub_id', $value->sid)->where(function($query){
                            $query->whereIn('status', [30, 32])->orWhere([['status', 10], ['is_merchant_do', 1]]);
                        })->orderBy('status', 'asc')->get()->toArray();
                        $auditFailCount = \DB::table('users_orders')->where('store_uid', $this->uid)->where(function($query){
                            $query->where('status', 30)->orWhere([['status', 10], ['is_merchant_do', 1]]);
                        })->count();
                        break;
                    default:
                }
                if( !count($value->list) ){
                    unset($data[$key]);
                }else{
                    foreach ($value->list as $key1 => &$value1) {
                        $user = \DB::table('users')->where('id', $value1->uid)->select(['name', 'avatar'])->first();
                        $value1->username = $user ? $user->name:"";
                        $value1->avatar = $user ? $user->avatar:"";
                        $value1->imgArr = $value1->imgs?\explode(',', $value1->imgs):[];
                        $allAmount += $value1->settle_amount;
                        $allFee += $value1->fee - $value1->discount_fee;
                    }
                }
            }
        }else{
            $data = \DB::table('users_orders')->where('store_uid', $this->uid)->whereDate('created_at', $date)->where('status', 50)->orderBy('id', 'desc')->get()->toArray();
            foreach ($data as $key1 => &$value1) {
                $user = \DB::table('users')->where('id', $value1->uid)->select(['name', 'avatar'])->first();
                $value1->username = $user ? $user->name:"";
                $value1->avatar = $user ? $user->avatar:"";
                $value1->store_type = \DB::table('stores_info')->where('id', $value1->store_info_id)->value("type");
                $allAmount += $value1->settle_amount;
                $allFee += $value1->fee - $value1->discount_fee;
            }
        }

        return returnJson(0, '', ['list'=>$data, 'time'=>$time,'notSettle'=>$notSettle, 'auditOk'=>$auditOkCount,'allAmount'=>$allAmount, 'allFee'=>$allFee, 'auditFailCount'=>$auditFailCount]);
    }
    /**
     * 标记通过
     */
    public function auditOk(){
        $this->uid = \session('uid');
        $id = \request()->input('id');
        $order = UsersOrders::where([
            ['id', $id],
        ])->first();
        if( !$order ){
            return returnJson(1, '订单有误');
        }

        if( !in_array($order->status, [10, 30, 32, 35]) ){
            return returnJson(1, '订单状态无法操作通过');
        }

//        查看任务
        $sub = \DB::table('subsidy')->where('id', $order->sub_id)->first();
        if( !$sub ){
            return returnJson(1, '订单信息有误，无法操作');
        }
        if( $sub->uid != $this->uid ){
            return returnJson(1, '您无权操作此订单');
        }
        $order->status = 40;
        
        if( $order->save() ){
            return returnJson();
        }
        return returnJson(1, '复审失败,请重新提交');
    }

    /**
     * 复审驳回
     */
    public function auditFail(){
        $this->uid = \session('uid');
        $id = \request()->input('id');
        $type = \request()->input('type');//1-驳回到第一步，2-驳回到第二步
        $fail_reason = \request()->input('fail_reason');
        $order = UsersOrders::where([
            ['id', $id],
        ])->first();
        if( !$order ){
            return returnJson(1, '订单有误');
        }

        if( $order->status != 35 ){
            return returnJson(1, '订单状态驳回');
        }

//        查看任务
        $sub = \DB::table('subsidy')->where('id', $order->sub_id)->first();
        if( !$sub ){
            return returnJson(1, '订单信息有误，无法操作');
        }
        if( $sub->uid != $this->uid ){
            return returnJson(1, '您无权操作此订单');
        }

        $order->fail_reason = $fail_reason;
        if( $type == 1 ){
            $order->refuse_status = 10;
            $order->is_need_ali_audit = 0;
            $order->overdue = date("Y-m-d H:i:s", time()+1800);
        }else{
            $order->overdue = date("Y-m-d 15:59:59", time()+3600*24);
            $order->refuse_status = 30;
        }
        $order->status = 32;
        $order->is_merchant_do = 1;
        

        if( $order->save() ){
            return returnJson();
        }
        return returnJson(1, '复审失败,请重新提交');
    }
}
